// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { feedApi } from '/api/feed'
import { mallApi } from '/api/mall'
import { userApi } from '/api/user'
import { checkAuth, getDomoUser } from '/store/actions'
import { getAppId, getServer, isLogin, onNews } from '/store/mutations'
import { $utils } from '/utils'
Page({
  data: {
    navData: [
      { name: '总排行榜', id: 1, page: 0, isLastpage: false },
      { name: '今日排行榜', id: 2, page: 0, isLastpage: false },
      { name: '球员排行榜', id: 3, page: 0, isLastpage: false },
      { name: '主播排行榜', id: 4, page: 0, isLastpage: false }
    ],
    scrollLeft: 0,
    cur: 1,
    cur2: 0,
    current_user_free_votes: 0,
    current_user_payed_votes: 0,
    query: {
      only_video: false,
      category: 0 as number,
      limit: 10,
    },
    showConfirm: false,
    showPayConfirm: false,
    showPayConfirm2: false,
    buyCount: 0,
    hasMore: true,
    page: 1,
    list: [] as any[],
    follower: false,
    scrollClass: false,
    user: {},
    currentIndex: 1,
    teamlist: [] as any,
    vote_user_id: 0,
    options: {},
    /** 总价(单位:元) */
    countPrice: 0,
    /** 总价(单位:分) */
    countPrices: 0,
    count: 1,
    orig: true,
    realname: 'yaoyao',
    phone: '13699999999',
    province: '湖南',
    city: '长沙',
    country: 'AAA区',
    detail: '长江路',
  },
  async onLoad(options?: any) {
    console.log(options)
    await this.fetchUsers(1)
    const info = await mallApi.getCommodityDetail(43)
    this.setData({
      commodityId: options.commodityId,
      orig: options.orig === '1' ? true : false,
      info,
      options: info.options ? info.options[0] : '',
      count: options.orig === '1' ? 1 : info.order_min_qty || 1,
      sku: info.sku ? info.sku[0] : {},
    })
  },
  async loadMore() {
    console.log(this.data.hasMore)
    const index = this.data.currentIndex
    if (this.data.hasMore) {
      this.data.page++
      await this.fetchUsers(index)
    }
  },
  choosePayVote(e: any) {
    const id = e.currentTarget.dataset.id as number
    // const commodityId = 43
    const buy_count = id
    const buy_total_price = buy_count
    // 调用接口
    this.setData({ showPayConfirm2: true })
    this.setData({ buyCount: buy_count })
    console.log('总价格 是' + buy_total_price + '元')
    // wx.navigateTo({
    //   url: `/pages/match/payvote/pay?commodityId=${commodityId}&orig=1&count=${buy_count}&total_price=${buy_total_price}`,
    // })
  },
  doPayVote(e: any) {
  },
  async doVote(e: any) {
    this.setData({ showConfirm: true })
    const userId = this.data.vote_user_id
    const voteResult = await feedApi.voteTeamer({
      votes_number: 1,
      vote_type: 1,
      to_user_id: userId
    })
    if (voteResult.errorcode === 0) {
      if (this.data.cur === 0) {
        console.log('cur2 is ' + this.data.cur2)
        this.fetchNewUsers(this.data.cur2)
      } else {
        console.log('cur is ' + this.data.cur)
        this.fetchNewUsers(this.data.cur)
      }
      wx.showToast({
        title: '投票成功！',
        icon: 'none',
        duration: 1000,
      })
    } else {
      wx.showToast({
        title: voteResult.message,
        icon: 'none',
        duration: 1000,
      })
    }
    this.setData({ showConfirm: false })
  },
  vote(e: any) {
    const userId = e.currentTarget.dataset.id as number
    const free_number = e.currentTarget.dataset.freenumber as number
    this.setData({ current_user_free_votes: free_number })
    console.log('当前用户的免费投票次数是' + free_number)
    this.setData({ vote_user_id: userId })
    if (isLogin()) {
      if (free_number > 0) {
        this.setData({ showPayConfirm: true })
      } else {
        this.setData({ showConfirm: true })
      }
      getDomoUser()
    } else {
      checkAuth()
    }
  },
  async onPullDownRefresh() {
    if (this.data.cur === 0) {
      console.log('onPullDownRefresh:cur2 is ' + this.data.cur2)
      this.fetchNewUsers(this.data.cur2)
    } else {
      console.log('onPullDownRefresh:cur is ' + this.data.cur)
      this.fetchNewUsers(this.data.cur)
    }
    wx.stopPullDownRefresh()
  },
  async onReachBottom() {
    console.log('onReachBottom')
    const index = this.data.currentIndex
    if (this.data.hasMore) {
      wx.showToast({
        title: '加载中',
        icon: 'none',
        duration: 1000,
      })
      this.data.page++
      await this.fetchUsers(index)
    }
  },
  /** 关闭弹窗 */
  closeConfirm() {
    this.setData({ showPayConfirm: false })
    this.setData({ showConfirm: false })
    this.setData({ showPayConfirm2: false })
  },
  /** 关闭付费弹窗 */
  closeConfirm2() {
    this.setData({ showPayConfirm2: false })
    this.setData({ showPayConfirm: true })
    this.setData({ showConfirm: false })
  },
  onPageScroll() {
    this.fixedTitle()
  },
  onShareAppMessage() {
    return {
      path: $utils.getSharePath(),
    }
  },
  async onSubmit() {
    const userId = this.data.vote_user_id
    try {
      await onNews(['{{MERCHANT_SHIPPING_KEY}}'])
    } catch (error) {
      // wx.showToast({ title: '请配置正确的订阅消息key，具体位置在package.json', icon: 'none' })
    }
    if (!userId || userId === 0) {
      wx.showToast({ title: '没有找到正确的被投票用户', icon: 'none' })
      return
    }
    this.closeConfirm()
    this.setData({ submitLock: true })
    try {
      const payInfo = await mallApi.postMallOrder({
        commodity_id: 43,
        vote_to_user_id: userId,
        commodity_option: this.data.options,
        is_orig_price: this.data.orig,
        user_remark: '',
        pay_score: 0,
        address: {
          name: this.data.realname,
          phone: this.data.phone,
          province: this.data.province,
          city: this.data.city,
          country: this.data.country,
          detail: this.data.detail,
        },
        openid: wx.getStorageSync(`${getServer()}/openId`).data,
        appid: getAppId() ? getAppId() : '{{APP_ID}}',
        quantity: this.data.buyCount,
      })
      if (payInfo.pay_amount === 0) {
        this.payShowToast(true)
        return
      }
      wx.requestPayment({
        ...payInfo.pay_data,
        success: () => {
          if (this.data.cur === 0) {
            console.log('payed:cur2 is ' + this.data.cur2)
            this.fetchNewUsers(this.data.cur2)
          } else {
            console.log('payed:cur is ' + this.data.cur)
            this.fetchNewUsers(this.data.cur)
          }
          this.payShowToast(true)
        },
        fail: () => {
          this.payShowToast(false)
        },
      })
    } catch (error) {
      wx.showToast({
        title: `${getMessage(error.data).getMessage()}`,
        icon: 'none',
      })
    }
  },
  payShowToast(success: boolean) {
    this.setData({
      payToast: true,
      paySuccess: success,
    })
  },
  /** 判断是否滚动到了导航 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#header').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollClass: res[0] && res[0].bottom < 0,
      })
    })
  },

  toChangeCurrent(e: WechatMiniprogram.BaseEvent) {
    const id = e.currentTarget.dataset.id as number
    console.log(id)
    if (id === this.data.cur) return
    this.setData({
      cur: id,
      cur2: 0,
      page: 1,
      teamlist: [],
      hasMore: true,
    })
    this.setData({
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60,
    })
    this.updateCurrentTable(id)
  },
  toChangeCurrent2(e: WechatMiniprogram.BaseEvent) {
    const id = e.currentTarget.dataset.id as number
    console.log(id)
    if (id === this.data.cur2) return
    this.setData({
      cur2: id,
      cur: 0,
      page: 1,
      teamlist: [],
      hasMore: true,
    })
    this.setData({
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60,
    })
    this.updateCurrentTable2(id)
  },
  async changeCurrent(e: any) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    this.updateCurrentTable(index)
  },

  async updateCurrentTable(index: any) {
    const {
      data: {
        navData,
        query: { },
      },
    } = this
    this.setData(
      {
        currentIndex: parseInt(index),
        category: navData[parseInt(index) - 1] ? navData[parseInt(index) - 1].id : 5,
        method: index < 2 ? 'normal' : 'hot',
        query: {
          ...this.data.query,
        },
      },
      async () => {
        const loaded = wx.getStorageSync(`loaded_${index}`)
        console.log(loaded)
        // 是否加载过，没有加载过则执行首次加载
        if (
          loaded !== true ||
          (loaded === true && (this.data.teamlist[index] || []).length === 0)
        ) {
          console.log(index)
          // const list = await this.fetchMatchList()
          await this.fetchUsers(parseInt(index))
          // this.setData({
          //   teamlist: teamlist.data,
          // })
        }
      },
    )
  },

  async updateCurrentTable2(index: any) {
    console.log(index)
    const {
      data: {
        query: { },
      },
    } = this
    this.setData(
      {
        currentIndex: parseInt(index),
        method: index < 2 ? 'normal' : 'hot',
        query: {
          ...this.data.query,
        },
      },
      async () => {
        const loaded = wx.getStorageSync(`loaded_${index}`)
        // 是否加载过，没有加载过则执行首次加载
        if (
          loaded !== true ||
          (loaded === true && (this.data.teamlist[index] || []).length === 0)
        ) {
          console.log(index)
          // const list = await this.fetchMatchList()
          await this.fetchUsers(parseInt(index))
          // this.setData({
          //   teamlist: teamlist.data,
          // })
        }
      },
    )
  },
  chooseTab(e: WechatMiniprogram.BaseEvent) {
    const index = e.currentTarget.dataset.index
    if (index === this.data.cur) return
    this.setData({
      cur: index,
    })
    if (this.data.list[this.data.cur]) return
    this.fetchMatchList()
  },

  async fetchUsers(feedId: number) {
    const userOldList = this.data.teamlist
    let t = ''
    if (feedId === 1) {
      t = 'all'
    } else if (feedId === 2) {
      t = 'today'
    } else if (feedId === 3) {
      t = 'ball'
    } else if (feedId === 4) {
      t = 'zhubo'
    }
    try {
      const teamUserList = await userApi.getJimengRank({
        play_type: feedId,
        page: this.data.page,
        pageSize: 10,
        show_type: t, // 分页列表数据类型  all 和 today
      })
      console.log(teamUserList)
      if (teamUserList.length === 0) {
        this.setData({ hasMore: false })
        wx.showLoading({
          title: '已经没有更多了！',
        })
        wx.hideLoading()
      } else {
        for (const key in teamUserList) {
          if (typeof teamUserList[key].avatar !== 'string' && teamUserList[key].avatar) {
            teamUserList[key].avatar = teamUserList[key].avatar.url
          } else {
            teamUserList[key].avatar = ''
          }
          if (teamUserList[key].bio && teamUserList[key].bio.length > 60) {
            teamUserList[key].bio = teamUserList[key].bio.slice(0, 60) + '...'
          }
          userOldList.push(teamUserList[key])
        }
        this.setData({
          teamlist: userOldList,
        })
      }
    } catch (error) {
      console.log(error)
    }
  },
  // 重新刷新用户列表
  async fetchNewUsers(feedId: number) {
    let t = ''
    if (feedId === 1) {
      t = 'all'
    } else if (feedId === 2) {
      t = 'today'
    } else if (feedId === 3) {
      t = 'ball'
    } else if (feedId === 4) {
      t = 'zhubo'
    }
    this.setData({
      page: 1,
      hasMore: true,
    })
    const userOldList = []
    try {
      const teamUserList = await userApi.getJimengRank({
        play_type: feedId,
        page: 1,
        pageSize: 10,
        show_type: t, // 分页列表数据类型  all 和 today
      })
      console.log(teamUserList)
      if (teamUserList.length === 0) {
        this.setData({ hasMore: false })
        wx.showLoading({
          title: '已经没有更多了！',
        })
        wx.hideLoading()
      } else {
        for (const key in teamUserList) {
          if (typeof teamUserList[key].avatar !== 'string' && teamUserList[key].avatar) {
            teamUserList[key].avatar = teamUserList[key].avatar.url
          } else {
            teamUserList[key].avatar = ''
          }
          if (teamUserList[key].bio && teamUserList[key].bio.length > 60) {
            teamUserList[key].bio = teamUserList[key].bio.slice(0, 60) + '...'
          }
          userOldList.push(teamUserList[key])
        }
        this.setData({
          teamlist: userOldList,
        })
      }
    } catch (error) {
      console.log(error)
    }
  },
  async fetchMatchList(isLoadMore = false): Promise<DomoMatchListsData> {
    wx.showLoading({
      title: '加载中',
    })
    const {
      data: { query },
    } = this
    this.setData({
      loading: true,
    })
    const matchlist = await feedApi.getMatchList({
      limit: query.limit,
      category_id: this.data.currentIndex,
      page: 1,
      audited: 1,
      admin_sort: 'down',
    })
    wx.setStorageSync(`loaded_match_1`, true)
    this.setData({ loading: false })
    wx.hideLoading()
    return matchlist
  },
  async follower(e: WechatMiniprogram.BaseEvent) {
    if (this.data.follower) return
    this.setData({
      follower: true,
    })
    const index = e.currentTarget.dataset.index
    const cur = this.data.cur
    const list = this.data.list[cur]
    this.setData({
      [`list[${cur}][${index}].has_follower`]: !list[index].has_follower,
      follower: false,
    })
    wx.showToast({
      title: list[index].has_follower ? '关注成功' : '已取消关注',
      icon: 'none',
      duration: 1000,
    })
  },
})
